package itcast.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import itcast.domain.User;
import itcast.service.UserService;
import itcast.service.UserServiceimpl;

/**
 * Servlet implementation class AddUserServlet
 */
@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//解决保存文件乱码问题
		response.setCharacterEncoding("utf-8");//解决保存文件乱码问题
		doGet(request, response);
		//1、设置编码 
		
		//2、获取提交注册信息
		String name=request.getParameter("name");
		String gender=request.getParameter("gender");//性别
		int age=Integer.parseInt(request.getParameter("age"));
		String address=request.getParameter("address");
		String qq=request.getParameter("qq");
		String email=request.getParameter("email");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		//3、定义user封装起来
		User user=new User();
		user.setName(name);
		user.setGender(gender);
		user.setAge(age);
		user.setAddress(address);
		user.setQq(qq);
		user.setEmail(email);
		user.setUsername(username);
		user.setPassword(password);
		//4、调用service层传入对象
		UserService service=new UserServiceimpl();
		int count=0;
		//5、通过返回值判断是否成功
		count=service.addUser(user);
		if (count==1) {
			//1、注册成功的跳转到页面！
			//2、需要完善的东西就是注册页面要求信息正确无误才可提交！
			//request.getRequestDispatcher("userlistServlet").forward(request, response);
			request.getRequestDispatcher("login.jsp").forward(request, response);
			System.out.println("注册成功");
		}else {
			//response.sendRedirect("Register.jsp");
			request.setAttribute("loser", "请规范填写！");	
			request.getRequestDispatcher("Register.jsp").forward(request, response);
			System.out.println("失败");
		}
	}

}
